package cn.yangliu.ueditor;

import cn.yangliu.ueditor.utils.UEUtils;
import com.baidu.ueditor.UEditorConfig;
import com.baidu.ueditor.web.ShowServlet;
import com.baidu.ueditor.web.UEditorServlet;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 作者 杨柳
 * 创建时间 2017-09-04 00:26
 * 启动ueditor的配置
 */
@Configuration
@EnableConfigurationProperties(value = UEditorProperties.class)
//@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "spring.ueditor", value = "enable", matchIfMissing = true)
public class UEditorAutoConfiguration {

    @Resource
    private UEditorProperties properties;

    /**
     * @return 初始化ueditor配置
     */
    @Bean
    public UEditorConfig uEditorConfig() {
        UEditorConfig config = new UEditorConfig();
        //设置统一访问前缀
        config.setGlobalUrlPreffix(properties.getGlobalUrlPreffix());
        //设置统一保存路径前缀
        config.setGlobalSavePathPreffix(properties.getGlobalSavePathPreffix());
        //设置工具栏
        config.setToolbars(properties.getToolbars());
        config.createConfig(UEUtils.getConfigProperties(properties));
        return config;
    }


    @Bean
    public ServletRegistrationBean ueditorShowServletRegistrationBean(){
        ServletRegistrationBean bean = new ServletRegistrationBean();
        ShowServlet showServlet = new ShowServlet();
        bean.setServlet(showServlet);
        String url = properties.getGlobalUrlPreffix();
        String defaultUrl = "/ueShow";
        if (StringUtils.isEmpty(url)) {
            url = defaultUrl;
        }
        if (url.startsWith("http://") || url.startsWith("https://")) {
            url = defaultUrl;
        }
        url = url + "/*";
        bean.addUrlMappings(url);
        return bean;
    }

    @Bean
    public ServletRegistrationBean ueditorControllerServletRegistrationBean(){
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new UEditorServlet());
        bean.addUrlMappings(properties.getServerUrl());
        return bean;
    }

}
